<?php

namespace app\admin\controller\financing;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Env;

/**
 * 诊疗销售费用录入
 *
 * @icon fa fa-user
 */
class Order extends Backend
{


    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $models = null;
    protected $categorylist = [];
    private $redis;

    public function _initialize()
    {
        parent::_initialize();
        //$this->model = new \app\admin\model\Registration;
        $this->model = new \app\admin\model\Accepts;
        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["users"=>['id','name'],"medic"=>['id','name'],"info"=>['id','name']])
                //->with(["users"=>['id','nickname','phone']])
                ->with([
                    'info' => function ($query) {
                        $query->withField('id,name');
                    }
                ])
                ->where($where)
                ->where('Accepts.status','in','1,2')
                ->order('update_time', 'desc')
                ->paginate($limit);

            if (!empty($list->items())){
                foreach ($list->items() as $k=>$v){
                    $treatment = Db::table('fa_treatment')
                        ->alias('a')
                        ->field('a.id,a.salesman_id,b.nickname')
                        ->join('fa_admin b','a.salesman_id=b.id','left')
                        ->where(['a.order_id'=>$v['id'],'a.finish'=>1])
                        ->select();
                    $list->items()[$k]['str'] = '';
                    if (!empty($treatment)){
                        foreach ($treatment as $kk=>$vv){
                            if (!empty($vv['nickname'])){
                                $list->items()[$k]['str'] .= ','.$vv['nickname'];
                            }
                        }
                    }

                    if (!empty($list->items()[$k]['str'])){
                        $eth_name = explode(',',$list->items()[$k]['str']);
                        unset($eth_name[0]);
                        $eth_name = array_unique($eth_name);
                        $list->items()[$k]['str'] = implode(',',$eth_name);
                    }
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if (!is_numeric($params['traffic'])){
                $this->error(__('交通（治疗）不是数字'));
            }

            if (!is_numeric($params['stay'])){
                $this->error(__('住宿（治疗）不是数字'));
            }

            if (!is_numeric($params['repast'])){
                $this->error(__('餐饮（治疗）不是数字'));
            }

            if (!is_numeric($params['traffics'])){
                $this->error(__('交通（开发维护）不是数字'));
            }

            if (!is_numeric($params['stays'])){
                $this->error(__('住宿（开发维护）不是数字'));
            }

            if (!is_numeric($params['repasts'])){
                $this->error(__('餐饮（开发维护）不是数字'));
            }

            if (!is_numeric($params['discounted'])){
                $this->error(__('折扣费不是数字'));
            }

            if (!is_numeric($params['royalties'])){
                $this->error(__('提成费不是数字'));
            }

            if (!is_numeric($params['commission'])){
                $this->error(__('代理费不是数字'));
            }

            if (!is_numeric($params['totals'])){
                $this->error(__('合计不是数字'));
            }

            $params['entry'] = 1;
            $params['entry_time'] = time();
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }




}
